package com.study.shengsiyuan.example09;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

public class _2_NioServer {
	private static Map<String,SocketChannel>  clientMap =new HashMap<>();

	public static void main(String[] args) throws IOException {
		ServerSocketChannel ssc = ServerSocketChannel.open();
		ssc.configureBlocking(false);
		ssc.bind(new InetSocketAddress(8899));
		Selector selector = Selector.open();
		ssc.register(selector, SelectionKey.OP_ACCEPT);

		while(true) { // select() : 返回关注事件的数量,是阻塞方法
			selector.select();
			Set<SelectionKey>  ssks =selector.selectedKeys();

			ByteBuffer bb = ByteBuffer.allocate(1024);
			for (SelectionKey selectionKey : ssks) {
				SocketChannel client =null;
				if(selectionKey.isAcceptable()) {
					bb.clear();
					ServerSocketChannel server = (ServerSocketChannel)selectionKey.channel();
					client = server.accept();
					client.configureBlocking(false);
					client.register(selector, selectionKey.OP_READ);
					String key ="【"+client.getRemoteAddress()+"】";
					clientMap.put(key, client);
				}else if (selectionKey.isReadable()) {
					bb.clear();
					client = (SocketChannel)selectionKey.channel();
					int count =client.read(bb);
					if(count>0) {
						bb.flip();
						Charset charset = Charset.forName("UTF-8");
						String receivemsg = String.valueOf(charset.decode(bb).array());
						System.out.println(client + "  发送的信息 ： " + receivemsg);

						String senderKey =null;
						for (Entry<String, SocketChannel> entry : clientMap.entrySet()) {
							if(entry.getValue() == client) {
								senderKey=entry.getKey();
								break;
							}
						}
						for (Entry<String, SocketChannel> entry : clientMap.entrySet()) {
							bb.clear();
							SocketChannel value = entry.getValue();
							bb.put( (senderKey+"发送的消息  : "+receivemsg).getBytes() );
							bb.flip();
							value.write(bb);
						}
					}

				}
				ssks.remove(selectionKey);
			}
		}
	}
}
